import { login, logout, getInfo, listRouters } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, {constantRoutes} from '@/router'
import Layout from "@/layout";
import store from "@/store";

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },

  mutations: {
    RESET_STATE: (state) => {
      Object.assign(state, user)
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_ROUTERS: (state, routers) => {
      state.routers = routers
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const imgCode = userInfo.imgCode
      const imgToken = userInfo.imgToken
      return new Promise((resolve, reject) => {
        login({username, password, imgCode, imgToken}).then(res => {
          commit('SET_TOKEN', res.data.accessToken)
          setToken(res.data.accessToken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const { data } = res
          const { roles, username } = res.data
          let avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          if (data.avatar) {
            avatar = data.avatar
          }
          commit('SET_ROLES', roles)
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)

          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户路由
    ListRouters({ commit, state }) {

      return new Promise(resolve => {
        listRouters().then(resp => {
          // 后台路由转为组件对象
          const routers = filterAsyncRouter(resp.data)
          router.addRoutes(routers) // 动态添加路由
          // 同时把后台路由加到路由列表
          commit('SET_ROUTERS', constantRoutes.concat(routers))

          resolve(routers)
        })
      })

    },

    // 退出系统
    LogOut({ commit, state }) {
      removeToken()
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_NAME', '')
          commit('SET_PERMISSIONS', [])
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // remove token
    resetToken({ commit }) {
      return new Promise(resolve => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resolve()
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(routers) {
  const accessedRouters = routers.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') { // Layout组件特殊处理
        route.component = Layout
      } else {
        // route.component = import('@/views/' + route.component + '.vue') // 导入组件
        route.component = loadView(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}

function loadView(view) {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

export default user
